/*
 * @Author: zi.yang
 * @Date: 2022-02-03 22:42:41
 * @LastEditors: zi.yang
 * @LastEditTime: 2022-02-07 10:01:14
 * @Description: user services
 * @FilePath: \api-generator\app\service\user.js
 */
'use strict';
const Service = require('egg').Service;
const Encryption = require('../utils/encryption');
const AjaxResponse = require('../utils/AjaxResponse');

class UserService extends Service {
  /**
   * 登录
   * @param { Object } 用户信息
   * @return { AjaxResponse }
   */
  async login({ username, password }) {
    const { ctx } = this;
    const userInfo = await ctx.model.User.findOne({ username });

    if (!userInfo) return AjaxResponse.error('用户名密码输入错误！');

    const ciphertext = Encryption.$pwd(password, userInfo.salt);
    const checkPassword = userInfo.password === ciphertext;

    if (!checkPassword) return AjaxResponse.error('用户名密码输入错误！');

    return AjaxResponse.success({ msg: '登陆成功！', data: userInfo });
  }

  /**
   * 添加用户
   * @param { Object } userInfo
   * @return { AjaxResponse }
   */
  async add(userInfo) {
    const { ctx } = this;
    try {
      await ctx.model.User.create(userInfo);
      return AjaxResponse.success({ msg: '用户创建成功！', data: userInfo });
    } catch (error) {
      return AjaxResponse.error({ msg: '用户创建失败！', error });
    }
  }

  /**
   * 根据 ID 查询用户
   * @param { String|Number } uid
   * @return { AjaxResponse }
   */
  async getUserById(uid) {
    const { ctx } = this;
    try {
      const userInfo = await ctx.model.User.findById(uid);
      if (userInfo) {
        return AjaxResponse.success({ msg: '用户创建成功！', data: userInfo });
      }
      return AjaxResponse.error({ code: 405, msg: '未检索到该用户' });
    } catch (error) {
      return AjaxResponse.error({ msg: '用户创建失败！', error });
    }
  }
}
module.exports = UserService;
